<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Random;
use think\Validate;
use think\Db;
use fast\Http;
use addons\third\library\Service;
use app\common\library\Auth;
use addons\third\model\Third;
use app\admin\model\Need;
use app\admin\model\User as ModelUser;
use think\Config;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'miniGetuserinfo', 'character_list', 'third','miniapplogin'];
    protected $noNeedRight = '*';

    protected $token = '';
    public function _initialize()
    {
        $this->token = $this->request->post('token');
        if ($this->request->action() == 'login' && $this->token) {
            $this->request->post(['token' => '']);
        }
        parent::_initialize();
    }
  
    /**
     * 小程序获取用户授权数据的接口
     * @ApiSummary  (小程序用户授权后把头像和昵称信息储存到数据库)
     * @ApiMethod   (POST)
     * @ApiParams   (name="openid", type="string", required=true, description="微信openid")
     * @ApiParams   (name="rawData", type="string", required=true, description="微信获取的rawData")
     */
    public function miniGetuserinfo()
    {
        $openid = $this->request->post("openid");
        $rawData = $this->request->post("rawData");
        if (!$rawData) {
            $this->error($rawData);
        }

        $rawData = htmlspecialchars_decode($rawData);
        $userInfo = (array)json_decode($rawData, true);

        $platform = 'wxapp';
        $result = [
            'openid'        => $openid,
            'userinfo'      => [
                'nickname' => $userInfo['nickName'],
            ],
        ];
        $extend = ['gender' => $userInfo['gender'], 'nickname' => $userInfo['nickName'], 'avatar' => $userInfo['avatarUrl']];
        
        // 第三方登录入库
        $ret = Service::connect($platform, $result, $extend);
        if ($ret) {
            //登录成功后的用户数据操作
            $auth = Auth::instance();

            $this->success("微信授权成功", ['userInfo' => $auth->getUserinfo()]);
        } else {
            $this->error("微信授权失败");
        }
    }

    /**
     * 小程序登录接口
     * @ApiSummary  (小程序登录接口)
     * @ApiMethod   (POST)
     * @ApiParams   (name="code", type="string", required=true, description="微信获取的code")
     * @ApiReturnParams   (name="openid", type="string", required=true, description="openid")
     * @ApiReturnParams   (name="http_result", type="string", required=true, description="wx登录返回的数据")
     */
    public function miniapplogin()
    {
        $config = get_addon_config('third');    
        $config = $config['wechat'];

        $code = $this->request->post("code");
        if (!$code) {
            $this->error("参数不正确");
        }
        
        $params = [
            'appid'      => $config['app_id'],
            'secret'     => $config['app_secret'],
            'js_code'    => $code,
            'grant_type' => 'authorization_code'
        ];

        $http_result = Http::sendRequest("https://api.weixin.qq.com/sns/jscode2session", $params, 'GET');

        if ($http_result['ret']) {
            $json = (array)json_decode($http_result['msg'], true);
            if (isset($json['openid'])) {
                
                $platform = 'wxapp';
                $result = [
                    'openid'        => $json['openid'],
                    'access_token'  => $json['session_key'],
                    'expires_in'    => isset($json['expires_in']) ? $json['expires_in'] : 0,
                ];
                // 第三方登录入库
                // 在user表创建一条新用户数据
                $ret = Service::connect($platform, $result);

                if ($ret) {
                    //登录成功后的用户数据操作
                    $auth = Auth::instance();

                    $this->success("登录成功", ['http_result' => $json,'openid'=>$json['openid'],'token' => $auth->getUserinfo()['token']]);
                } else {
                    $this->error("连接失败");
                }
            } else {
                $this->error("登录失败",$http_result['msg']);
            }
        }

        return;
    }

    /**
     * 获取角色列表
     */
    public function character_list(){
        $return = [];
        $parent_list = Db::name('category')->where(['type'=>'character','pid'=>0])->field('name,id')->order('weigh desc')->select();
        $return = $parent_list;
        foreach ($parent_list as $key => $value) {
            $return[$key]['child_list'] = Db::name('category')->where(['pid'=>$value['id']])->field('name,id')->order('weigh desc')->select();
        }
        $this->success('获取角色列表',$return);
    }

     /**
     * 修改用户信息 (pid是角色类型的id)
     * @param int $pid
     * @param string $avatar
     * @param string $birthday
     * @param string $nickname
     */
    public function edit(){
        $user = $this->auth->getUser();
        $pid = input('pid');
        $avatar = input('avatar');
        $nickname = input('nickname');
        $birthday = input('birthday');
        if ($pid) {
            $user->pid = $pid;
        }
        if($avatar){
            $user->avatar = $avatar;
        }
        if ($birthday) {
            $user->birthday = $birthday;
        }
        if($nickname){
            $user->nickname = $nickname;
        }
        
        $user->save();
        $this->success('修改成功');
    }
    
    /**
     * 会员信息
     * @ApiSummary  (category_text 是角色类型，money是累计收入，nickname是昵称,coupon_num是优惠券数量)
     * @ApiMethod   (GET)
     */
    public function index()
    {
        $userInfo = $this->auth->getUserinfo();
        $ModelUser = New ModelUser();
        $return = $ModelUser::get($userInfo['user_id']);
        $start = strpos($return['avatar'], 'avatar.png');
        if(!empty($start)){
            $return['avatar'] = Config('site.cdnurl').$return['avatar'];
        }
        $this->success('会员信息', $return);
    }
    /**
    * 优惠券接口 expired 是已过期,used 是已使用,no_used 是未使用
    */
    public function juan(){
        $userInfo = $this->auth->getUserinfo();
        $juan = Db::name('juan')->field("*,FROM_UNIXTIME(createtime,'%Y-%m-%d %H:%i:%s') as createtime")->where('user_id',$userInfo['user_id'])->select();
        $now_time = time();
        $jian_time = $now_time-604800;
        $return = [];
        foreach ($juan as $key => $value) {
            if($value['state']=='1'){
                $return['used'][] = $value;
            }
            if($value['state']=='0'){
                if($value['createtime']<$jian_time){
                    $return['expired'][] = $value;
                }else{
                    $return['no_used'][] = $value;
                }
            }
        }
        $this->success('优惠券接口',$return);
    }

    /**
     * 我的收藏列表 mission是任务列表，need是需求列表。mission下的category_text是类型名称
     */
    public function my_collect(){
        $userInfo = $this->auth->getUserinfo();
        $self_data = Db::name('collect')->where('user_id',$userInfo['user_id'])->find();

        $need_id_array = json_decode($self_data['need_id'],true);
        $mission_id_array = json_decode($self_data['mission_id'],true);
        $data_id_array = json_decode($self_data['data_id'],true);


        $Need = New Need();
        $need = Need::all($need_id_array);
        $return['need'] = $need;
        $return['mission'] = Db::name('mission')->where('id','in',$mission_id_array)->field('id,detail,title,num,remaining')->select();
        $return['data'] =  Db::name('data')->where('id','in',$data_id_array)->field('id,title,area,detail')->select();


        $this->success('我的收藏列表',$return);
    }

    /**
     * 我参与的(join_mission_list是任务，join_need_list是需求)
     */
    public function my_join(){
        $userInfo = $this->auth->getUserinfo();
        $return['join_mission_list'] = Db::name('join_mission')->where('user_id',$userInfo['user_id'])->select();
        $return['join_need_list'] = Db::name('join_need')->where('user_id',$userInfo['user_id'])->select();
        $this->success('我参与的',$return);
    }

    /**
     * 放弃我的参与
     * @ApiSummary  ()
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/user/quit)
     * @ApiParams   (name="id",type=int,required=true,description="任务或者需求id")
     * @ApiParams   (name="state",type=int,required=true,description="放弃任务时传1，放弃需求时不用传1就行")
     * @ApiReturn ({
        
     })
     */
     public function quit(){
        $id = input('id');
        $state = input('state');
        $userInfo = $this->auth->getUserinfo();
        if($state=='1'){
            Db::name('join_mission')->where(['mission_id'=>$id,'user_id'=>$userInfo['user_id']])->delete();
        }else{
            Db::name('join_need')->where(['need_id'=>$id,'user_id'=>$userInfo['user_id']])->delete();
        }

        $this->success('放弃成功');

     }


    /**
     * 我的发布列表(on上架列表,off是下架列表,mission_list_on是任务，need_list_off是需求)
     */
    public function fabu_list(){
        $userInfo = $this->auth->getUserinfo();
        $mission_list_on = Db::name('mission')->where('user_id',$userInfo['user_id'])->where('status',1)->field('id,title,total_price,num,remaining')->order('updatetime desc')->select();
        $mission_list_off = Db::name('mission')->where('user_id',$userInfo['user_id'])->where('status',0)->field('id,title,total_price,num,remaining')->order('updatetime desc')->select();

        $Need = New Need();
        $need_list_on = $Need->where(['user_id'=>$userInfo['user_id'],'status'=>1])->order('updatetime desc')->select();

        $need_list_off = $Need->where(['user_id'=>$userInfo['user_id'],'status'=>0])->order('updatetime desc')->select();

        $return['on']['mission_list_on'] = $mission_list_on; 
        $return['on']['need_list_on'] = $need_list_on; 

        $return['off']['mission_list_off'] = $mission_list_off; 
        $return['off']['need_list_off'] = $need_list_off; 

        $this->success('我的发布列表',$return);
    }

    
}
